package com.nf.nf.common.interceptors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.nf.nf.common.support.ApiData;
import com.nf.nf.model.TbSysUser;
import com.nf.nf.service.TbSysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <功能简述>
 * 
 * @author cris
 */
@Component
public class ApiAuthInterceptor implements HandlerInterceptor {
    private static final Logger logger = LogManager.getLogger(ApiAuthInterceptor.class);

    // 白名单
    private List<String> whiteUrls;

    private int _size = 0;

    @PostConstruct
    public void init(){
        // 读取文件
        String path = ApiAuthInterceptor.class.getResource("/").getFile();
        whiteUrls = readFile(path + "tokenWhite.txt");
        _size = null == whiteUrls ? 0 : whiteUrls.size();
    }

    @Resource
    private TbSysUserService loginService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // synchronized(this){

        String token = req.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = req.getParameter("token");
        }
        //String url = req.getServletPath();

        if (isWhiteReq(req.getRequestURI())) {
            return true;
        }
        if (token != null) {
            try {
                Long time = Long.valueOf(token.substring(32));
                if (System.currentTimeMillis() <= time) {
                    TbSysUser usertk = new TbSysUser();
                    usertk.setToken(token);
                    TbSysUser tempUser = loginService.getOne(new QueryWrapper<TbSysUser>(usertk));
                    if (null != tempUser) {
                        return true;
                    } else {
                        ApiData data = new ApiData();
                        data.setResult(2000);
                        this.setResult2Json(resp, data);
                        return false;
                    }
                } else {
                    ApiData data = new ApiData();
                    data.setResult(2000);
                    this.setResult2Json(resp, data);
                    return false;
                }
            } catch (Exception e) {
                ApiData data = new ApiData();
                data.setResult(2000);
                this.setResult2Json(resp, data);
                return false;
            }
        } else {
            ApiData data = new ApiData();
            data.setResult(2000);
            this.setResult2Json(resp, data);
            return false;
        }

    }

    public void setResult2Json(HttpServletResponse resp, Object obj) throws IOException {

        Gson gson = new Gson();
        String result = gson.toJson(obj);
        resp.setContentType("text/json; charset=utf-8");
        resp.setHeader("Cache-Control", "no-cache"); // 取消浏览器缓存
        PrintWriter out = resp.getWriter();
        out.print(result);
        out.flush();
        out.close();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    private List<String> readFile(String fileName) {
        List<String> list = new ArrayList<String>();
        BufferedReader reader = null;
        FileInputStream fis = null;
        try {
            File f = new File(fileName);
            if (f.isFile() && f.exists()) {
                fis = new FileInputStream(f);
                reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (!"".equals(line)) {
                        list.add(line);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("readFile", e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                logger.error("InputStream关闭异常", e);
            }
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                logger.error("FileInputStream关闭异常", e);
            }
        }
        return list;
    }

    /*
     * 判断是否是白名单
     */
    private boolean isWhiteReq(String requestUrl) {
        if (_size == 0) {
            return false;
        } else {
            for (String urlTemp : whiteUrls) {
                if (requestUrl.indexOf(urlTemp) != -1 ||
                        requestUrl.indexOf(urlTemp.toLowerCase()) != -1) {
                    return true;
                }
            }
        }

        return false;
    }
}
